package top.healthylife.basics.utils.utils;

import java.util.List;

/**
 * 自定义List分页工具
 *
 * @author maoxiaomeng
 */
public class PageUtil {

    /**
     * 开始分页
     *
     * @param list List<T>
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return List<T>
     */
    public static <T> List<T> startPage(List<T> list, Long pageNum,
                                        Long pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        // 记录总数
        Long count = (long) list.size();
        // 页数
        long pageCount = 0L;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        // 开始索引
        long fromIndex;
        // 结束索引
        long toIndex;

        if (pageNum == null || pageNum < 1L) {
            pageNum = 1L;
        }
        if (pageNum > pageCount) {
            pageNum = pageCount;
        }

        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        return list.subList((int) fromIndex, (int) toIndex);
    }
}